<template>
  <div>
    <el-cascader
      v-model="selectedValues"
      :options="treeData"
      :props="cascaderProps"
      @change="handleChange"
    />
    <p>选中值: {{ formattedValues }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rawData: [
        { content: "文本A", isChoose: "N", parentTag: "1", tagId: "1.1" },
        { content: "文本B", isChoose: "N", parentTag: "1", tagId: "1.2" },
        { content: "文本C", isChoose: "N", parentTag: "1.2", tagId: "1.2.1" },
        { content: "文本D", isChoose: "N", parentTag: "2", tagId: "2.1" },
        { content: "文本E", isChoose: "N", parentTag: "2.1", tagId: "2.1.1" },
        { content: "文本F", isChoose: "N", parentTag: null, tagId: "3" },
        { content: "文本G", isChoose: "N", parentTag: "3", tagId: "3.1" },
        { content: "文本H", isChoose: "N", parentTag: "3.1", tagId: "3.1.1" },
        { content: "文本I", isChoose: "N", parentTag: "4", tagId: "4.1" },
        { content: "文本J", isChoose: "N", parentTag: "4", tagId: "4.2" },
        { content: "文本K", isChoose: "N", parentTag: "4.2", tagId: "4.2.1" },
      ],
      treeData: [],
      selectedValues: [],
      cascaderProps: {
        value: "tagId",
        label: "content",
        multiple: true,
        checkStrictly: true,
        emitPath: false,
      },
      formattedValues: [],
    };
  },
  created() {
    this.treeData = this.transformToTree(this.rawData);
  },
  methods: {
    transformToTree(data) {
      const map = new Map();

      // 初始化节点
      data.forEach((item) => {
        map.set(item.tagId, { ...item, children: [] });
      });

      const result = [];

      data.forEach((item) => {
        if (item.parentTag === null) return; // 不显示
        const node = map.get(item.tagId);
        const parent = map.get(item.parentTag);
        if (item.parentTag.includes(".")) {
          // 二级节点
          if (parent) parent.children.push(node);
        } else {
          // 一级节点
          result.push(node);
        }
      });

      // children 为空则设为 null
      const cleanChildren = (arr) =>
        arr.map((i) => ({
          ...i,
          children: i.children.length ? cleanChildren(i.children) : null,
        }));

      return cleanChildren(result);
    },
    handleChange(values) {
      this.formattedValues = `[${values.join(",")}]`;
    },
  },
};
</script>
